package com.wht.sip.core.transmit;


import cn.hutool.core.util.StrUtil;
import com.wht.sip.utils.SipUtils;
import gov.nist.javax.sip.SipProviderImpl;
import lombok.extern.slf4j.Slf4j;
import org.noear.solon.annotation.Inject;
import org.noear.solon.annotation.Managed;

import javax.sip.SipException;
import javax.sip.header.CallIdHeader;
import javax.sip.header.UserAgentHeader;
import javax.sip.header.ViaHeader;
import javax.sip.message.Message;
import javax.sip.message.Request;
import javax.sip.message.Response;
import java.text.ParseException;

/**
 * 发送SIP消息
 *
 * @author lin
 */
@Slf4j
@Managed
public class SIPSender {

    @Inject(value = "tcpSipProvider")
    SipProviderImpl tcpSipProvider;

    @Inject(value = "udpSipProvider")
    SipProviderImpl udpSipProvider;

    public void transmitRequest(Message message) throws SipException {
        ViaHeader viaHeader = (ViaHeader) message.getHeader(ViaHeader.NAME);
        String transport = "UDP";
        if (viaHeader == null) {
            log.warn("[消息头缺失]： ViaHeader， 使用默认的UDP方式处理数据");
        } else {
            transport = viaHeader.getTransport();
        }
        if (message.getHeader(UserAgentHeader.NAME) == null) {
            try {
                message.addHeader(SipUtils.createUserAgentHeader());
            } catch (ParseException e) {
                log.error("添加UserAgentHeader失败", e);
            }
        }

        try {

            if ("TCP".equals(transport)) {

                if (message instanceof Request) {
                    tcpSipProvider.sendRequest((Request) message);
                } else if (message instanceof Response) {
                    tcpSipProvider.sendResponse((Response) message);
                }

            }

            if ("UDP".equals(transport)) {
                if (message instanceof Request) {
                    udpSipProvider.sendRequest((Request) message);
                } else if (message instanceof Response) {
                    udpSipProvider.sendResponse((Response) message);
                }
            }
        } catch (SipException e) {
            throw e;
        }
    }

    public CallIdHeader getNewCallIdHeader(String ip, String transport) {

        if (StrUtil.isEmpty(transport)) {
            return udpSipProvider.getNewCallId();
        }

        SipProviderImpl sipProvider = "TCP".equalsIgnoreCase(transport) ? tcpSipProvider : udpSipProvider;

        if (sipProvider == null) {
            sipProvider = udpSipProvider;
        }

        if (sipProvider != null) {
            return sipProvider.getNewCallId();
        } else {
            log.warn("[新建CallIdHeader失败]， ip={}, transport={}", ip, transport);
            return null;
        }
    }


}
